package tools;

import java.util.Iterator;

import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.MySQL5InnoDBDialect;
import org.hibernate.dialect.Oracle9Dialect;
import org.hibernate.dialect.OracleDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;

public class SchemaExportTool {

	public static void main(String[] args) throws Exception {
		String outputDir = "E:/";
		export(outputDir);
	}

	public static void export(String outputDir) throws Exception {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"classpath:applicationContext_test.xml");
		LocalSessionFactoryBean localSessionFactoryBean = applicationContext
				.getBean(LocalSessionFactoryBean.class);
		Configuration configuration = localSessionFactoryBean
				.getConfiguration();
		export(configuration, DBType.H2, outputDir);
	}

	@SuppressWarnings("unchecked")
	private static void export(Configuration configuration, DBType dbType,
			String outputDir) {
		configuration.setProperty("hibernate.dialect", dbType.getDialect());
		SchemaExport schemaExport = new SchemaExport(configuration);
		String output = outputDir + dbType.getType() + ".schema.sql";
		schemaExport.setOutputFile(output);

		String delimiter = ";";
		if (delimiter != null) {
			schemaExport.setDelimiter(delimiter);
		}

		// 是否在控制台输出脚本
		boolean scriptToConsole = true;
		// 是否将脚本导入数据库
		boolean export = false;
		schemaExport.create(scriptToConsole, export);
		for (Iterator<Exception> iter = schemaExport.getExceptions().iterator(); iter
				.hasNext();) {
			Exception e = iter.next();
			e.printStackTrace();
		}
	}

	public enum DBType {
		MySQL("MySQL", MySQL5InnoDBDialect.class.getName()), H2("H2",
				H2Dialect.class.getName()), SQLServer2005("SQLServer2005",
				SQLServerDialect.class.getName()), SQLServer2008(
				"SQLServer2008", SQLServerDialect.class.getName()), Oracle(
				"Oracle", OracleDialect.class.getName()), Oracle9("Oracle9",
				Oracle9Dialect.class.getName()), DB2("DB2", DB2Dialect.class
				.getName()), HSQL("HSQL", HSQLDialect.class.getName());

		private String type;

		private String dialect;

		private DBType(String type, String dialect) {
			this.type = type;
			this.dialect = dialect;
		}

		public String getType() {
			return type;
		}

		public String getDialect() {
			return dialect;
		}

	}

}
